package com.hxm.meizi.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.blankj.utilcode.utils.LogUtils;
import com.hxm.meizi.R;
import com.hxm.meizi.entity.ImageUrl;
import com.hxm.meizi.http.JsoupDoc;
import com.hxm.meizi.listener.ItemsRequestListener;
import com.hxm.meizi.provider.ImageListProvider;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by hxm on 2017/2/19.
 * 某一图片具体列表页
 */

public class ImageDetailFragment extends Fragment {
    private String imageKey;
    private RecyclerView recyclerView;
    private MultiTypeAdapter adapter;
    private ImageView progressBar;

    public static ImageDetailFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("key", url);
        ImageDetailFragment fragment = new ImageDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageKey = getArguments().getString("key");
        Log.i("hxm", "onCreate: " + imageKey);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image_detail, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        progressBar = (ImageView) view.findViewById(R.id.progress_bar);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    }

    private void initData() {
        JsoupDoc.getImageDetails(imageKey, new ItemsRequestListener(progressBar) {
            @Override
            public void onSuccess(Items items) {
                super.onSuccess(items);
                adapter = new MultiTypeAdapter(items);
                adapter.register(ImageUrl.class, new ImageListProvider(items));
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String reason) {
                super.onFailure(reason);
                LogUtils.i("Error", reason);
            }
        });
    }
}
